import fs from 'fs'
import path from 'path'
import http from 'http'
import https from 'https'

export class example extends plugin {
  constructor() {
    super({
      name: '风云图片',
      dsc: '18风云和acg风云图片',
      event: 'message',
      priority: 500,
      rule: [
        {
          reg: '^18风云$',
          fnc: 'fengyun18'
        },
        {
          reg: '^acg风云$',
          fnc: 'acgFengyun'
        }
      ]
    })
  }

  async fengyun18(e) {
    return await this.sendMultipleImages(e, 'https://xiaodi.jujukai.cn/Api/sj18r.php')
  }

  async acgFengyun(e) {
    return await this.sendMultipleImages(e, 'https://xiaodi.jujukai.cn/Api/ACG.php')
  }

  async sendMultipleImages(e, apiUrl) {
    try {
      // 先发送等待提示
      const waitMsg = await e.reply('正在获取风云图片，请稍候...')
      
      // 获取三张图片，带重试机制
      const imageBuffers = []
      let attempts = 0
      const maxAttempts = 15 // 增加最大尝试次数
      
      while (imageBuffers.length < 3 && attempts < maxAttempts) {
        attempts++
        try {
          const imageUrl = await this.getImageUrl(apiUrl)
          if (imageUrl) {
            const imageBuffer = await this.fetchImageBuffer(imageUrl)
            if (imageBuffer) {
              imageBuffers.push(imageBuffer)
              console.log(`成功获取第${imageBuffers.length}张图片`)
            }
          }
        } catch (err) {
          console.log(`获取图片失败 (尝试${attempts}/${maxAttempts}):`, err.message)
        }
        
        // 如果不是最后一张图片，短暂延迟
        if (imageBuffers.length < 3 && attempts < maxAttempts) {
          await this.sleep(500)
        }
      }
      
      // 删除等待提示
      if (waitMsg && waitMsg.message_id) {
        try {
          if (e.isGroup) {
            await e.group.recallMsg(waitMsg.message_id)
          } else {
            await e.friend.recallMsg(waitMsg.message_id)
          }
        } catch (err) {
          console.log('删除等待提示失败')
        }
      }

      if (imageBuffers.length === 0) {
        await e.reply('获取图片失败，请稍后重试')
        return true
      }

      // 一次性发送所有图片，使用分段发送避免1200错误
      const messageIds = []
      
      // 逐张发送图片，每张之间添加延迟
      for (let i = 0; i < imageBuffers.length; i++) {
        try {
          // 添加延迟避免发送过快
          if (i > 0) {
            await this.sleep(2000) // 2秒延迟
          }
          
          const ret = await e.reply([
            {
              type: 'image',
              file: `base64://${imageBuffers[i].toString('base64')}`
            },
            {
              type: 'text',
              text: `风云科技 ${i + 1}/${imageBuffers.length}`
            }
          ])
          
          if (ret && ret.message_id) {
            messageIds.push(ret.message_id)
            console.log(`成功发送第${i + 1}张图片`)
          }
        } catch (err) {
          console.log(`发送第${i + 1}张图片失败:`, err.message)
          
          // 如果发送失败，尝试使用更简单的消息格式
          try {
            await this.sleep(1000)
            const simpleRet = await e.reply(
              segment.image(`base64://${imageBuffers[i].toString('base64')}`)
            )
            if (simpleRet && simpleRet.message_id) {
              messageIds.push(simpleRet.message_id)
              console.log(`使用简单格式成功发送第${i + 1}张图片`)
            }
          } catch (err2) {
            console.log(`使用简单格式发送第${i + 1}张图片也失败:`, err2.message)
          }
        }
      }
      
      // 30秒后撤回所有消息
      if (messageIds.length > 0) {
        setTimeout(async () => {
          for (const msgId of messageIds) {
            try {
              if (e.isGroup) {
                await e.group.recallMsg(msgId)
              } else {
                await e.friend.recallMsg(msgId)
              }
            } catch (err) {
              console.log('撤回消息失败:', err.message)
            }
          }
          console.log(`${messageIds.length}张风云图片已自动撤回`)
        }, 120000)
      }

      return true

    } catch (error) {
      console.error('获取图片失败:', error)
      await e.reply('获取图片失败，请稍后重试')
      return true
    }
  }

  // 获取图片的最终URL（处理302重定向）
  async getImageUrl(apiUrl) {
    return new Promise((resolve, reject) => {
      const httpModule = apiUrl.startsWith('https') ? https : http
      
      const options = {
        rejectUnauthorized: false,
        headers: {
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
      }
      
      const request = httpModule.get(apiUrl, options, (response) => {
        // 处理重定向
        if (response.statusCode === 302 || response.statusCode === 301) {
          const redirectUrl = response.headers.location
          if (redirectUrl) {
            resolve(redirectUrl)
          } else {
            reject(new Error('重定向但没有提供URL'))
          }
          return
        }
        
        if (response.statusCode !== 200) {
          reject(new Error(`HTTP error! status: ${response.statusCode}`))
          return
        }

        // 如果不是重定向，直接返回原URL
        resolve(apiUrl)
      })
      
      request.on('error', (err) => {
        reject(err)
      })
      
      request.setTimeout(10000, () => {
        request.destroy()
        reject(new Error('请求超时'))
      })
    })
  }

  // 获取图片数据
  async fetchImageBuffer(url) {
    return new Promise((resolve, reject) => {
      const httpModule = url.startsWith('https') ? https : http
      
      const options = {
        rejectUnauthorized: false,
        headers: {
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
          'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8'
        }
      }
      
      const request = httpModule.get(url, options, (response) => {
        if (response.statusCode !== 200) {
          reject(new Error(`HTTP error! status: ${response.statusCode}`))
          return
        }

        const chunks = []
        response.on('data', (chunk) => chunks.push(chunk))
        response.on('end', () => {
          const buffer = Buffer.concat(chunks)
          if (buffer.length < 100) {
            reject(new Error('返回数据过小，可能不是有效的图片'))
          } else {
            resolve(buffer)
          }
        })
      })
      
      request.on('error', (err) => {
        reject(err)
      })
      
      request.setTimeout(10000, () => {
        request.destroy()
        reject(new Error('请求超时'))
      })
    })
  }

  // 简单的sleep函数
  sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
  }
}